<template>
  <el-form
    ref="form"
    label-width="5em"
    v-loading="formLoading"
    :model="form"
    :rules="rules"
  >
    <el-form-item label="题干" prop="titleContent">
      <el-input
        type="textarea"
        v-model="form.titleContent"
        :disabled="isDisabled"
      />
    </el-form-item>
    <el-form-item label="答案" prop="correct">
      <el-input type="textarea" v-model="form.correct" :disabled="isDisabled" />
    </el-form-item>
    <el-form-item label="解析" prop="analyze">
      <el-input type="textarea" v-model="form.analyze" :disabled="isDisabled" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :disabled="isDisabled" @click="submitForm">
        保存
      </el-button>
      <el-button :disabled="isDisabled" @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getQuestionInfo } from "@/api2/question";

export default {
  inject: ["question"],
  data() {
    return {
      formLoading: false,
      form: {
        titleContent: "",
        correct: "",
        analyze: "",
      },
      rules: {
        titleContent: [
          { required: true, message: "请输入题干", trigger: "blur" },
        ],
        correct: [{ required: true, message: "请输入答案", trigger: "blur" }],
      },
    };
  },
  computed: {
    isDisabled() {
      return this.form.status == 2 || this.form.status == 3;
    },
  },
  mounted() {
    this.question?.id && this.getDetail();
  },
  methods: {
    async getDetail() {
      this.formLoading = true;
      const { data } = await getQuestionInfo({ id: this.question.id });
      this.form = data;
      this.formLoading = false;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true;
          this.$emit("submit", this.form, () => {
            this.formLoading = false;
            !this.question?.id && this.resetForm()
          });
        }
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  margin-right: 1em;
}
</style>
